import axios from 'axios'
import router from '../router'
// import {AppAccessToken} from './AppConstant.js'
import {Message} from 'element-ui'
import store from '../store/index'
const GetCaptchaPath = 'api/AppUserVc/appLoginCaptcha'

export class ResponseError extends Error {
  constructor (message, code) {
    super(message)
    Message.error(message)

    this.name = 'ResponseError'
    this.code = code
    // 这一步可不写，默认会保存堆栈追踪信息到自定义错误构造函数之前，
    // 而如果写成 `Error.captureStackTrace(this)` 则自定义错误的构造函数也会被保存到堆栈追踪信息
    Error.captureStackTrace(this, this.constructor)
  }
}

const ajax = axios.create({
  // baseURL: process.env.VUE_APP_API_BASE_URL + '',
  timeout: 10000
})

// 请求拦截（配置发送请求的信息）
ajax.interceptors.request.use((config) => {
  // 处理请求之前的配置
  if (store.getters.isLogined) {
    config.headers = {
      'Authorization': 'Bearer ' + store.state.userInfo.token
    }
  }
  return config
}, function (error) {
  // 请求失败的处理
  return Promise.reject(error)
})

// 响应拦截（配置请求回来的信息）
ajax.interceptors.response.use((response) => {
  // 处理响应数据
  if (response.status !== 200 && response.status !== 201) {
    return Promise.reject(new ResponseError('操作失败(' + response.status + ')', response.status))
  }

  if (response.request.responseURL.indexOf(GetCaptchaPath) > 0) {
    // 拦截获取验证码
    return response.data
  }

  if (response.data.code === null || response.data.code === undefined) {
    return Promise.reject(new ResponseError('解析code失败', 1000))
  }

  if (response.data.code !== 2000) {
    if (response.data.code === 2002 || response.data.code === 401) {
      // window.location = '/'
      router.push({name: 'Login'})
    }
    if (response.data.msg && (response.data.msg + '').trim().length > 0) {
      return Promise.reject(new ResponseError(response.data.msg, response.data.code))
    }
    return Promise.reject(new ResponseError('操作失败(' + response.data.code + ')', response.data.code))
  }
  // 直接返回数据
  return response.data
}, function (error) {
  if (error.message.includes('timeout')) {
    // 判断请求异常信息中是否含有超时timeout字符串
    Message.error('请求超时')
    return Promise.reject(error)
  } else if (error.message) {
    Message.error(error.message)
  } else {
    Message.error(error)
  }

  return Promise.reject(error)
})

// export default ajax
export function get (url, param = {}) {
  return new Promise((resolve, reject) => {
    ajax({method: 'get', url: url}).then(res => {
      if ((url + '').indexOf(GetCaptchaPath) >= 0) {
        resolve(res)
      } else {
        resolve(res.result)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    ajax({method: 'post', url, data: data}).then(res => {
      resolve(res.result)
    }).catch(err => {
      reject(err)
    })
  })
}
